using System;
using System.Collections.Generic;
using UnityEngine;

namespace GenerativeAgents.Core
{
    /// <summary>
    /// 原始事件数据结构
    /// 表示从环境中提取的未处理事件
    /// </summary>
    [System.Serializable]
    public class RawEvent
    {
        public string id;                   // 事件ID
        public EventType type;              // 事件类型
        public string subject;              // 主语
        public string predicate;            // 谓语
        public string objectEntity;         // 宾语
        public Vector3 location;            // 位置
        public DateTime timestamp;          // 时间戳
        public Dictionary<string, object> metadata; // 元数据
        
        public RawEvent()
        {
            id = System.Guid.NewGuid().ToString();
            timestamp = DateTime.Now;
            metadata = new Dictionary<string, object>();
        }
    }
    
    /// <summary>
    /// 查询数据结构
    /// 用于记忆检索的查询请求
    /// </summary>
    [System.Serializable]
    public class MemoryQuery
    {
        [Header("查询内容")]
        public string queryText;            // 查询文本
        public float[] queryEmbedding;      // 查询嵌入向量
        public List<string> keywords;       // 关键词
        
        [Header("查询参数")]
        public int maxResults;              // 最大结果数
        public float recencyWeight;         // 新近度权重
        public float importanceWeight;      // 重要性权重
        public float relevanceWeight;       // 相关性权重
        
        [Header("过滤条件")]
        public List<MemoryType> typeFilter; // 类型过滤
        public DateTime? timeAfter;         // 时间过滤：之后
        public DateTime? timeBefore;        // 时间过滤：之前
        public Vector3? locationCenter;     // 位置过滤：中心
        public float? locationRadius;       // 位置过滤：半径
        public List<string> participantFilter; // 参与者过滤
        
        [Header("查询上下文")]
        public string agentName;            // 查询的智能体名称
        public Vector3 currentLocation;     // 当前位置
        public QueryContext context;        // 查询上下文
        
        public MemoryQuery()
        {
            keywords = new List<string>();
            typeFilter = new List<MemoryType>();
            participantFilter = new List<string>();
            maxResults = 10;
            recencyWeight = 0.3f;
            importanceWeight = 0.3f;
            relevanceWeight = 0.4f;
            context = QueryContext.General;
        }
        
        /// <summary>
        /// 创建简单文本查询
        /// </summary>
        public static MemoryQuery CreateTextQuery(string text, int maxResults = 10)
        {
            return new MemoryQuery
            {
                queryText = text,
                maxResults = maxResults
            };
        }
        
        /// <summary>
        /// 创建对话上下文查询
        /// </summary>
        public static MemoryQuery CreateConversationQuery(string topic, string participant, int maxResults = 5)
        {
            var query = new MemoryQuery
            {
                queryText = topic,
                maxResults = maxResults,
                context = QueryContext.Conversation
            };
            query.participantFilter.Add(participant);
            query.typeFilter.Add(MemoryType.Chat);
            query.typeFilter.Add(MemoryType.Event);
            return query;
        }
        
        /// <summary>
        /// 创建计划上下文查询
        /// </summary>
        public static MemoryQuery CreatePlanningQuery(string goal, Vector3 location, int maxResults = 8)
        {
            return new MemoryQuery
            {
                queryText = goal,
                maxResults = maxResults,
                context = QueryContext.Planning,
                locationCenter = location,
                locationRadius = 20f // 20米范围内的相关记忆
            };
        }
        
        /// <summary>
        /// 创建反思上下文查询
        /// </summary>
        public static MemoryQuery CreateReflectionQuery(string focusPoint, DateTime timeStart, int maxResults = 15)
        {
            return new MemoryQuery
            {
                queryText = focusPoint,
                maxResults = maxResults,
                context = QueryContext.Reflection,
                timeAfter = timeStart,
                importanceWeight = 0.5f, // 反思时更重视重要性
                recencyWeight = 0.3f,
                relevanceWeight = 0.2f
            };
        }
    }
    
    /// <summary>
    /// 查询上下文
    /// </summary>
    public enum QueryContext
    {
        General,        // 通用查询
        Conversation,   // 对话上下文
        Planning,       // 计划上下文
        Reflection,     // 反思上下文
        Navigation,     // 导航上下文
        Social          // 社交上下文
    }
    
    /// <summary>
    /// 计划项数据结构
    /// </summary>
    [System.Serializable]
    public class PlanItem
    {
        [Header("计划基础信息")]
        public string planId;               // 计划ID
        public string description;          // 描述
        public string action;               // 具体行动
        public Vector3 targetLocation;      // 目标位置
        public string locationName;         // 位置名称
        
        [Header("时间信息")]
        public DateTime scheduledTime;      // 计划时间
        public TimeSpan estimatedDuration;  // 预估持续时间
        public DateTime? actualStartTime;   // 实际开始时间
        public DateTime? actualEndTime;     // 实际结束时间
        
        [Header("计划状态")]
        public PlanStatus status;           // 计划状态
        public int priority;                // 优先级
        public bool isInterruptible;        // 是否可中断
        
        [Header("依赖和条件")]
        public List<string> prerequisites;  // 前置条件
        public List<string> dependencies;   // 依赖的其他计划
        public Dictionary<string, object> conditions; // 执行条件
        
        [Header("相关信息")]
        public List<string> involvedAgents; // 涉及的其他智能体
        public List<string> requiredObjects; // 需要的物品
        public string motivation;           // 动机
        
        public PlanItem()
        {
            planId = System.Guid.NewGuid().ToString();
            status = PlanStatus.Planned;
            priority = 5;
            isInterruptible = true;
            prerequisites = new List<string>();
            dependencies = new List<string>();
            conditions = new Dictionary<string, object>();
            involvedAgents = new List<string>();
            requiredObjects = new List<string>();
        }
        
        /// <summary>
        /// 检查计划是否可以执行
        /// </summary>
        public bool CanExecute()
        {
            return status == PlanStatus.Planned && 
                   DateTime.Now >= scheduledTime &&
                   ArePrerequisitesMet();
        }
        
        /// <summary>
        /// 检查前置条件是否满足
        /// </summary>
        private bool ArePrerequisitesMet()
        {
            // 简化实现，实际应该检查具体的前置条件
            return prerequisites.Count == 0; // 临时实现
        }
        
        /// <summary>
        /// 开始执行计划
        /// </summary>
        public void StartExecution()
        {
            status = PlanStatus.InProgress;
            actualStartTime = DateTime.Now;
        }
        
        /// <summary>
        /// 完成计划
        /// </summary>
        public void Complete()
        {
            status = PlanStatus.Completed;
            actualEndTime = DateTime.Now;
        }
        
        /// <summary>
        /// 取消计划
        /// </summary>
        public void Cancel(string reason = "")
        {
            status = PlanStatus.Cancelled;
            if (!string.IsNullOrEmpty(reason))
            {
                conditions["cancellationReason"] = reason;
            }
        }
    }
    
    /// <summary>
    /// 计划状态
    /// </summary>
    public enum PlanStatus
    {
        Planned,        // 已计划
        InProgress,     // 执行中
        Paused,         // 暂停
        Completed,      // 已完成
        Cancelled,      // 已取消
        Failed          // 失败
    }
    
    /// <summary>
    /// 智能体状态
    /// </summary>
    [System.Serializable]
    public class AgentState
    {
        [Header("基础状态")]
        public string currentAction;        // 当前行动
        public Vector3 currentLocation;     // 当前位置
        public string currentLocationName;  // 当前位置名称
        public string mood;                 // 心情
        public float energy;                // 能量等级 (0-1)
        
        [Header("社交状态")]
        public bool isInConversation;       // 是否在对话中
        public string conversationPartner;  // 对话伙伴
        public string conversationTopic;    // 对话主题
        
        [Header("计划状态")]
        public string currentPlanId;        // 当前计划ID
        public DateTime lastPlanUpdate;     // 最后计划更新时间
        public bool needsReplanning;        // 是否需要重新计划
        
        [Header("记忆状态")]
        public int importanceTriggerCurrent; // 当前重要性触发器
        public int importanceTriggerMax;     // 最大重要性触发器
        public DateTime lastReflectionTime; // 最后反思时间
        
        public AgentState()
        {
            currentAction = "idle";
            mood = "neutral";
            energy = 1f;
            isInConversation = false;
            needsReplanning = false;
            importanceTriggerCurrent = 150; // 默认触发阈值
            importanceTriggerMax = 150;
            lastReflectionTime = DateTime.Now;
            lastPlanUpdate = DateTime.Now;
        }
    }
}